﻿using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Content.Res;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Util;
using Android.Widget;
using AndroidX.AppCompat.App;
using NightPlayer.views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NightPlayer
{
    [Activity(Label = "播放器设置")]
    internal class SettingActivity : BaseActivity
    {
        private Button btnCreateShortcut;
        private TextView lblProfileId;
        private Switch chkUdpMusicSwitch;
        private Button btnRescanMusicLibrary;
        private Switch chkCacheMusicLibrary;
        private Switch chkEinkMode;
        private Switch chkSleepTimerAwakeAwareness;
        private Switch chkLockscreenSwitchMusic;
        private void initUI()
        {
            btnCreateShortcut = (Button)FindViewById(Resource.Id.btnCreateShortcut);
            lblProfileId = (TextView)FindViewById(Resource.Id.lblProfileId);
            chkUdpMusicSwitch = (Switch)FindViewById(Resource.Id.chkUdpMusicSwitch);
            btnRescanMusicLibrary = (Button)FindViewById(Resource.Id.btnRescanMusicLibrary);
            chkCacheMusicLibrary = (Switch)FindViewById(Resource.Id.chkCacheMusicLibrary);
            chkSleepTimerAwakeAwareness = (Switch)FindViewById(Resource.Id.chkSleepTimerAwakeAwareness);
            chkEinkMode = (Switch)FindViewById(Resource.Id.chkEinkMode);
            chkLockscreenSwitchMusic = (Switch)FindViewById(Resource.Id.chkLockscreenSwitchMusic);
        }
        protected override void OnCreate(Bundle? savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_settings);
            initUI();
            FindViewById(Resource.Id.btnBack).Click += (sender, e) => Finish();

            chkEinkMode.Checked = Program.AppSettings.IsEink;
            chkCacheMusicLibrary.Checked = Program.AppSettings.PreferLibraryCache;
            chkLockscreenSwitchMusic.Checked = Program.AppSettings.UseLockscreenMusicSwitch;
            chkUdpMusicSwitch.Checked = Program.AppSettings.UDPMusicSwitch;
            chkSleepTimerAwakeAwareness.Checked = Program.AppSettings.SleepTimerAwareness;

            chkEinkMode.CheckedChange += (s, e) => Program.AppSettings.IsEink = e.IsChecked;
            chkCacheMusicLibrary.CheckedChange += (s, e) => Program.AppSettings.PreferLibraryCache = e.IsChecked;
            chkLockscreenSwitchMusic.CheckedChange += (s, e) => Program.AppSettings.UseLockscreenMusicSwitch = e.IsChecked;
            chkUdpMusicSwitch.CheckedChange += (s, e) => Program.AppSettings.UDPMusicSwitch = e.IsChecked;
            chkSleepTimerAwakeAwareness.CheckedChange += (s, e) => Program.AppSettings.SleepTimerAwareness = e.IsChecked;

            btnRescanMusicLibrary.Click += BtnRescanMusicLibrary_Click;

            lblProfileId.Text = PlayerService.prefslot ?? "<NULL>";

            btnCreateShortcut.Click += BtnCreateShortcut_Click;
        }

        private void BtnCreateShortcut_Click(object? sender, EventArgs e)
        {
            ShowEditorBox("创建快捷方式", "请填写配置文件名称，只能以大小写字母数字组成，不超过12位。", PlayerService.prefslot, shortcutNameValidation, (str) =>
            {
                CreateShortCut(str, createSlotIntent(str));
            });
        }

        private Intent createSlotIntent(string slotName)
        {
            Intent intent = new Intent(Intent.ActionMain);
            intent.SetComponent(new ComponentName(this,PackageName+".LauncherActivity"));
            intent.PutExtra("slot", slotName);
            return intent;
        }

        Func<string, bool> shortcutNameValidation = (str) =>
        {
            // 验证str是否仅为英文大小写字母和数字且不为空且不超过12位，且首个字符不能是数字
            return !string.IsNullOrEmpty(str) &&
                   System.Text.RegularExpressions.Regex.IsMatch(str, @"^[a-zA-Z][a-zA-Z0-9]{0,11}$");
        };


        /// <summary>
        /// 显示一个带有输入框的对话框，用于获取用户输入并进行验证
        /// </summary>
        /// <param name="title">对话框的标题</param>
        /// <param name="subtitle">对话框中显示的副标题文本</param>
        /// <param name="initialValue">输入框的初始值</param>
        /// <param name="validation">验证用户输入的函数，返回true表示验证通过，false表示验证失败</param>
        /// <param name="callback">当验证通过时执行的回调函数，接收用户输入作为参数</param>
        private void ShowEditorBox(string title, string subtitle, string initialValue, Func<string, bool> validation, Action<string> callback)
        {
            var builder = new Android.App.AlertDialog.Builder(this);
            builder.SetTitle(title);
            builder.SetCancelable(false); // 点击对话框外面不会关闭对话框

            // 创建布局
            var layout = new LinearLayout(this)
            {
                Orientation = Android.Widget.Orientation.Vertical
            };
            var pad16dp = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 24, Resources.DisplayMetrics);
            layout.SetPadding(pad16dp, pad16dp / 3, pad16dp, pad16dp / 3);

            // 添加TextView显示副标题
            var subtitleTextView = new TextView(this)
            {
                Text = subtitle,
                TextSize = 14f,
                
            };
            layout.AddView(subtitleTextView);

            // 添加EditText用于输入
            var inputEditText = new EditText(this)
            {
                Text = initialValue,
                TextSize = 16f
            };
            layout.AddView(inputEditText);

            // 设置自定义视图
            builder.SetView(layout);

            // 添加确定按钮
            builder.SetPositiveButton("确定", (sender, e) =>
            {
                string userInput = inputEditText.Text;
                if (validation(userInput))
                {
                    // 验证通过，执行回调
                    callback(userInput);
                }
                else
                {
                    ShowEditorBox(title, subtitle, userInput, validation, callback);
                }
            });

            // 添加取消按钮
            builder.SetNegativeButton("取消", (sender, e) =>
            {
                // 取消按钮不做任何操作，只是关闭对话框
            });

            // 创建并显示对话框
            var dialog = builder.Create();
            dialog.Show();
        }

        /// <summary>
        /// 为给定的Intent创建桌面快捷方式
        /// </summary>
        /// <param name="i">用于创建快捷方式的Intent</param>
        private void CreateShortCut(string label,Intent i)
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                // Android Oreo (API 26)及以上版本使用ShortcutManager
                var shortcutManager = (ShortcutManager)GetSystemService(ShortcutService);
                if (shortcutManager != null && shortcutManager.IsRequestPinShortcutSupported)
                {
                   
                    var info = new ShortcutInfo.Builder(this, "nightplayer_slot_"+label)
                        .SetIcon(Icon.CreateWithResource(this, Resource.Drawable.musicicon))
                        .SetShortLabel(label)
                        .SetIntent(i)
                        .Build();

                    shortcutManager.RequestPinShortcut(info, null);
                }
                else
                {
                    Toast.MakeText(this, "设备不支持快捷方式", ToastLength.Short).Show();
                }
            }
            else
            {


                var addIntent = new Intent();
                addIntent.PutExtra(Intent.ExtraShortcutIntent, i);
                addIntent.PutExtra(Intent.ExtraShortcutName, label);
                addIntent.PutExtra(Intent.ExtraShortcutIconResource,
                    Intent.ShortcutIconResource.FromContext(this, Resource.Drawable.musicicon));
                addIntent.SetAction("com.android.launcher.action.INSTALL_SHORTCUT");
                addIntent.PutExtra("duplicate", false); // 防止重复创建
                SendBroadcast(addIntent);
            }
        }


        


        private void BtnRescanMusicLibrary_Click(object? sender, EventArgs e)
        {
            Program.RequestClearCache();
            PlayerService.player?.AquireRaiseStop();
            Finish();
        }

        protected override void OnDestroy()
        {
            Program.SaveSettings(this);
            base.OnDestroy();
        }
    }
}
